package com.lfs.market.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lfs.market.exception.ServiceException;
import com.lfs.market.mapper.ProductVoucherMapper;
import com.lfs.market.model.dto.ProductVoucherCreateDto;
import com.lfs.market.model.entity.ProductVoucher;
import com.lfs.market.model.enums.ResultCode;
import com.lfs.market.service.ProductVoucherService;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;

@Service
public class ProductVoucherServiceImpl extends ServiceImpl<ProductVoucherMapper, ProductVoucher> implements ProductVoucherService {
    @Override
    public void create(ProductVoucherCreateDto dto) {
        ProductVoucher one = lambdaQuery().eq(ProductVoucher::getProductId, dto.getProductId()).one();
        if (BeanUtil.isEmpty(one)) {
            ProductVoucher productVoucher = new ProductVoucher();
            productVoucher.setProductId(dto.getProductId());
            productVoucher.setTitle("下单立减 " + dto.getVoucherValue() + " 元");
            BigDecimal voucherValue = dto.getVoucherValue();
            productVoucher.setVoucherValue(voucherValue.multiply(BigDecimal.valueOf(100)));
            productVoucher.setStock(1);
            LocalDateTime beginTime = LocalDateTime.ofInstant(Instant.ofEpochSecond(dto.getBeginTime()), ZoneId.systemDefault());
            LocalDateTime endTime = LocalDateTime.ofInstant(Instant.ofEpochSecond(dto.getEndTime()), ZoneId.systemDefault());
            productVoucher.setBeginTime(beginTime);
            productVoucher.setEndTime(endTime);
            productVoucher.setVoucherStatus(9);
            productVoucher.setCreateTime(new Date());
            productVoucher.setUpdateTime(new Date());
            boolean save = save(productVoucher);
            if (!save) {
                throw new ServiceException(ResultCode.SaveError);
            }
        } else {
            BigDecimal voucherValue = dto.getVoucherValue();
            one.setVoucherValue(voucherValue.multiply(BigDecimal.valueOf(100)));
            one.setStock(1);
            one.setTitle("优惠卷" + dto.getVoucherValue() + "元");
            one.setVoucherValue(voucherValue.multiply(BigDecimal.valueOf(100)));
            LocalDateTime beginTime = LocalDateTime.ofInstant(Instant.ofEpochSecond(dto.getBeginTime()), ZoneId.systemDefault());
            LocalDateTime endTime = LocalDateTime.ofInstant(Instant.ofEpochSecond(dto.getEndTime()), ZoneId.systemDefault());
            one.setBeginTime(beginTime);
            one.setEndTime(endTime);
            one.setVoucherStatus(9);
            one.setUpdateTime(new Date());
            boolean update = updateById(one);
            if (!update) {
                throw new ServiceException(ResultCode.UpdateError);
            }
        }

    }
}
